# 自定义jwt认证成功返回数据
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q

from users.models import User


def jwt_response_payload_handler(token, user=None, request=None):

    return {
        'token': token,
        'user_id': user.id,
        'username': user.username
    }

# 扩展登录接口支持使用手机号登录
class UsernameMobileAuthBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        # Q对象，取或
        query_set = User.objects.filter(Q(username=username) | Q(mobile=username))

        try:
            if query_set.exists():
                user = query_set.get()  # 取出一条数据
                if user.check_password(password):  # 判断密码是否正确
                    return user
        except:
            return None

